<template>
  <div class="bg-white m-4 mr-0 overflow-hidden">
    <a-spin :spinning="loading">
      <!--基础数据树-->
      <BasicTree v-if="!treeReloading" ref="treeRef" :treeData="treeData" toolbar
        :load-data="sync == false ? null : onLoadData" v-bind="getBindValue" @select="onSelect" @check="onCheck"
        :fieldNames="fieldNames" :selectedKeys="selectedKeys" :expandedKeys="expandedKeys" :checkedKeys="checkedKeys"
        :checkStrictly="getCheckStrictly" :clickRowToExpand="false" :search="true" @expand="onExpand" @search="onSearch"
        @reloadTree="reloadTree" @handleSearch="handleSelect" />
    </a-spin>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, ref, unref, provide } from 'vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { BasicTree, TreeActionType } from '/@/components/Tree';
import { treeList } from '../XlCustomerPurchaseUser.api';
import { treeProps } from '/@/components/Form/src/jeecg/props/props';
import { propTypes } from "/@/utils/propTypes";
import { useTreeBiz } from '/@/components/Form/src/jeecg/hooks/useTreeBiz';
import { useAttrs } from '/@/hooks/core/useAttrs';
import { omit } from 'lodash-es';

const emit = defineEmits(['select']);
// const { createMessage } = useMessage();

let loading = ref<boolean>(false);
// 列表数据
// let treeData = ref<any[]>([]);
// 当前展开的项
let expandedKeys = ref<any[]>([]);
// 当前选中的项
let selectedKeys = ref<any[]>(['0']);
// 是否自动展开父级
let autoExpandParent = ref<boolean>(true);
// 树组件重新加载
let treeReloading = ref<boolean>(false);

const attrs = useAttrs();
const treeRef = ref<Nullable<TreeActionType>>(null);
//页面参数初始化  
const props = defineProps({
  ...treeProps,
  sync: propTypes.bool.def(false),

  //初始展开的层级
  defaultExpandLevel: {
    type: [Number],
    default: 1,
  },
  //选择框标题
  modalTitle: {
    type: String,
    default: '渠道',
  },
  // update-begin--author:liaozhiyang---date:20231220---for：【QQYUN-7678】部门组件内容过多没有滚动条（给一个默认最大高）
  maxHeight: {
    type: Number,
    default: 500,
  },
  //是否显示选择按钮
  showButton: propTypes.bool.def(false),
  //是否显示复选框
  checkable: propTypes.bool.def(false),
  // 是否显示全选，默认 true
  isAll: propTypes.bool.def(true),
  // update-end--author:liaozhiyang---date:20231220---for：【QQYUN-7678】部门组件内容过多没有滚动条（给一个默认最大高）
  value: propTypes.oneOfType([propTypes.string, propTypes.array])
});
//update-begin-author:taoyan date:2022-10-28 for: 部门选择警告类型不匹配
let propValue = props.value === '' ? [] : props.value;
//update-begin-author:liusq date:2023-05-26 for:  [issues/538]JSelectDept组件受 dynamicDisabled 影响
let temp = Object.assign({}, unref(props), unref(attrs), { value: propValue }, { disabled: false });
const getBindValue = omit(temp, 'multiple');
//update-end-author:liusq date:2023-05-26 for:  [issues/538]JSelectDept组件受 dynamicDisabled 影响
//update-end-author:taoyan date:2022-10-28 for: 部门选择警告类型不匹配

const queryUrl = getQueryUrl();
const [{ visibleChange, checkedKeys, getCheckStrictly, getSelectTreeData, onCheck, onLoadData, treeData, checkALL, expandAll, selectRows }] =
  useTreeBiz(treeRef, queryUrl, getBindValue, props);
//替换treeNode中key字段为treeData中对应的字段
const fieldNames = {
  key: props.rowKey,
};



//默认设置为弹窗tree效果
visibleChange(true);

/** 获取查询数据方法 */
function getQueryUrl() {
  let queryFn = treeList;
  //update-begin-author:taoyan date:2022-7-4 for: issues/I5F3P4 online配置部门选择后编辑，查看数据应该显示部门名称，不是部门代码
  return (params) => queryFn(Object.assign({}, {
    ...params,
  }, { primaryKey: props.rowKey }));
  //update-end-author:taoyan date:2022-7-4 for: issues/I5F3P4 online配置部门选择后编辑，查看数据应该显示部门名称，不是部门代码
}


// 重新加载树组件，防止无法默认展开数据
async function reloadTree(type) {
  if (type) {
    expandedKeys.value = ['0'];
    selectedKeys.value = ['0'];
    emit('select', {
      key: '0',
      title: '全部',
      value: '0',
      id: '0',
      text: '全部',
      leaf: false,
      type: '1',
    },);
  }
  await nextTick();
  treeReloading.value = true;
  await nextTick();
  treeReloading.value = false;
}

/**
 * 设置当前选中的行
 */
function setSelectedKey(key: string, data?: object) {
  selectedKeys.value = [key];
  console.log(data)
  if (data) {
    emit('select', data);
  }
}

// 搜索事件
function onSearch(value: string) {
  if (!value.trim()) {
    // loadTreeData();
    onLoadData()
  }
}
function handleSelect(data) {
  selectedKeys.value = [data.key]
  emit('select', data);
}

// 树选择事件
function onSelect(selKeys, event) {
  if (selKeys.length > 0 && selectedKeys.value[0] !== selKeys[0]) {
    setSelectedKey(selKeys[0], event.selectedNodes[0]);
  } else {
    // 这样可以防止用户取消选择
    setSelectedKey(selectedKeys.value[0]);
  }
}

// 树展开事件
function onExpand(keys) {
  expandedKeys.value = keys;
  autoExpandParent.value = false;
}


function loadSelKey(selDate) {
  // provide('selectValues', keys);
  onLoadData();
  setTimeout(() => {
    checkedKeys.value = [selDate?.id];
    handleSelect(selDate);
  }, 500)
  // setSelectedKey(selectedKeys.value[0]);
  //下发 selectValues,xxxBiz组件接收
}
defineExpose({ onLoadData, visibleChange, reloadTree, loadSelKey, selectRows, selectedKeys })
</script>
<style lang="less" scoped>
/*升级antd3后，查询框与树贴的太近，样式优化*/
:deep(.jeecg-tree-header) {
  margin-bottom: 6px;
}
</style>